package bb.lanxing.service;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import bb.lanxing.App;
import bb.lanxing.common.engin.util.EnginUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.ProcessUtil;

public class DaemonService extends JobService {
    private static final String TAG = "DaemonService";
    private Handler jobHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            Log.logv(DaemonService.TAG, "JobService task running...");
            DaemonService.this.watchWorkoutService();
            DaemonService.this.jobFinished((JobParameters) message.obj, false);
            return true;
        }
    });

    public void watchWorkoutService() {
        boolean isServiceRunning = ProcessUtil.isServiceRunning(this, WorkoutRemoteService.class.getName());
        Log.logv(TAG, "JobService watchWorkoutService alive = " + isServiceRunning);
        if (!isServiceRunning) {
            startWorkoutService();
        }
    }

    private void startWorkoutService() {
        Intent intent = new Intent(App.getContext(), WorkoutRemoteService.class);
        intent.putExtra("daemon", true);
        intent.putExtra("record_open", EnginUtil.isRecordOpen());
        intent.putExtra("simulate_location", EnginUtil.isSimulateLocation());
        if (!App.getContext().isAppForeground()) {
            return;
        }
        App.getContext().startForegroundService(intent);
        return;
    }

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.logv(TAG, "JobService onStartJob");
        Handler handler = this.jobHandler;
        handler.sendMessage(Message.obtain(handler, 1, jobParameters));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.logv(TAG, "JobService onStopJob");
        this.jobHandler.removeMessages(1);
        return false;
    }
}
